<?php
/*
 * @Description:检修管理
 * @FilePath: \auxface_certificate\app\certificate\controller\user\v1\Repair.php
 */

declare (strict_types = 1);

namespace app\certificate\controller\user\v1;

use think\facade\Db;
use think\Request;

class Repair
{
    /**
     * @Description: 获取检修列表
     * @param {Request} $request
     */
    public function getList(Request $request)
    {
        $data        = $request->data;
        $limit       = $data['limit'];
        $page        = $data['page'];
        $searchWhere = [
            ['r.machineUuid', '=', $data['machineUuid']],
            ['r.isDelete', '=', '0'],
        ];
        //当前用户待填写的表单
        $getCurrentToSubFormUuids = $this->getCurrentToSubFormUuids($request->uuid) ?: [];
        //状态,待审核-0,审核通过-1，待填写-3
        if (!empty($data['status']) || (isset($data['status']) && $data['status'] == 0)) {
            if ($data['status'] == 3) {
                array_push($searchWhere, ['r.status', '=', 0]);
            } else {
                array_push($searchWhere, ['r.status', '=', $data['status']]);
            }
            //数据隔离
            if ($data['status'] == 3) {
                array_push($searchWhere, ['r.uuid', 'IN', $getCurrentToSubFormUuids]);
            } else {
                //获取当前提交过的检修
                $repairUuids = DB::table('certificate_digitalMachineRepairRecord')->where('wxappUserUuid', $request->uuid)->group('repairUuid')->column('repairUuid') ?? [];
                array_push($searchWhere, ['r.uuid', 'IN', $repairUuids]);
            }
        }

        $list = DB::table('certificate_digitalMachineRepair')
            ->alias('r')
            ->join('certification_projectWorker w', 'w.wxappUserUuid = r.wxappUserUuid', 'left')
            ->where($searchWhere)
            ->order(['r.id desc'])
            ->page((int) $page, (int) $limit)
            ->field(['w.workerName', 'r.inDate', 'r.status', 'r.uuid'])
            ->group('r.id')
            ->select()->toArray();
        foreach ($list as &$item) {
            $item['inDate'] = date('Y-m-d', strtotime($item['inDate']));
            //状态,待审核-0,审核通过-1
            if ($data['status'] == 3) {
                $item['status'] = '3'; //待填写
            }
        }
        $result['list'] = $list;
        //待填写数量
        $result['toSubCount'] = $this->getToSubCount($getCurrentToSubFormUuids, $data);
        //是否有新增权限,具有申请表权限+驾驶舱人员
        $result['hasAuth'] = $this->hasAuth($request, $data);

        return result(SUCCESS, $result, '');
    }

    /**
     * 获取详情
     *
     * @param Request $request
     * @return void
     */
    public function getDetail(Request $request)
    {
        $data  = $request->data;
        $uuid  = $data['uuid'];
        $where = [
            'r.isDelete' => 0,
            'r.uuid'     => $uuid,
        ];
        //查看有没有提交过的记录
        $repairData = DB::table('certificate_digitalMachineRepair')
            ->alias('r')
            ->where($where)
            ->order('r.id DESC')
            ->field(['r.status', 'r.uuid', 'r.title', 'r.description'])
            ->findOrEmpty();
        if (!$repairData) {
            return result(FAIL, '', '獲取失敗，請返回重試');
        }
        $repairRecord = DB::table('certificate_flowForm')
            ->alias('ff')
            ->join('certificate_digitalMachineRepairRecord r', 'r.flowFormUuid = ff.uuid')
            ->where('r.repairUuid', $uuid)
            ->order('ff.showOrder asc, ff.flowOrder asc,r.id asc')
            ->field('r.repairUuid,r.uuid,ff.name,ff.subtitle,r.formData')
            ->group('r.uuid')
            ->select()->toArray();
        foreach ($repairRecord as $key => $item) {
            $repairRecord[$key]['formData'] = json_decode(html_entity_decode($item['formData']), true);
        }
        $repairData['repairRecord'] = $repairRecord;

        $canSubFormUUids = $this->canSubForm($repairData['uuid']);

        $repairData['hasNext']     = $repairData['hasAuth']     = 0;
        $repairData['currentData'] = $repairData['nextData'] = [];
        //获取当前用户拥有的表单信息
        $currentFormData = DB::table('certificate_flowForm')
            ->alias('ff')
            ->join('certificate_flowFormWorker fw', 'fw.flowFormUuid = ff.uuid')
            ->where('fw.wxappUserUuid', $request->uuid)
            ->whereIn('ff.uuid', $canSubFormUUids)
            ->where('fw.isDelete', 0)
            ->order('ff.flowOrder asc')
            ->field('ff.uuid as formUuid,ff.name,ff.subtitle,ff.formData,ff.linkForms,ff.type,ff.flowUuid,ff.flowOrder')
            ->find();
        if ($currentFormData) {
            $formData                            = json_decode(html_entity_decode($currentFormData['formData']), true);
            $currentData['formData']['uuid']     = $currentFormData['formUuid'];
            $currentData['formData']['name']     = $currentFormData['name'];
            $currentData['formData']['subtitle'] = $currentFormData['subtitle'];
            $currentData['formData']['formData'] = $formData;
            $linkForms                           = $currentFormData['linkForms'] ? json_decode($currentFormData['linkForms'], true) : [];
            if ($linkForms) {
                $linkForms = DB::table('certificate_flowForm')
                    ->alias('ff')
                    ->join('certificate_digitalMachineRepairRecord r', 'r.flowFormUuid = ff.uuid')
                    ->whereIn('ff.uuid', $linkForms)
                    ->order('ff.showOrder asc,ff.flowOrder asc,r.id asc')
                    ->field('ff.uuid,ff.name,r.formData,ff.subtitle')
                    ->group('ff.uuid')
                    ->select()->toArray();
                foreach ($linkForms as $key => $item) {
                    $linkForms[$key]['formData'] = json_decode(html_entity_decode($item['formData']), true);
                }
            }

            //是否有下一次提交
            $canNextSubFormUUids = $this->canSubForm($repairData['uuid'], 0, $currentFormData['flowUuid'], $currentFormData['formUuid'], $currentFormData['flowOrder'], $currentFormData['type']);
            $nextFormData        = DB::table('certificate_flowForm')
                ->alias('ff')
                ->join('certificate_flowFormWorker fw', 'fw.flowFormUuid = ff.uuid')
                ->where('fw.wxappUserUuid', $request->uuid)
                ->whereIn('ff.uuid', $canNextSubFormUUids)
                ->where('fw.isDelete', 0)
                ->find();
            if ($nextFormData) {
                $repairData['hasNext']  = 1;
                $repairData['nextData'] = $nextFormData;
            }

            $currentData['linkForms']  = $linkForms;
            $repairData['currentData'] = $currentData;
            $repairData['hasAuth']     = 1;
        }
        return result(SUCCESS, $repairData, '');
    }

    public function checkMachineStatus($machineUuid, $repairUuid, $request)
    {
        $where = [
            ['machineUuid', '=', $machineUuid],
            ['isDelete', '=', 0],
            ['projectCode', '=', $request->prjCode],
            ['uuid', '<>', $repairUuid],
            ['status', '=', 0],

        ];
        // dd($where);
        $check = Db::table('certificate_digitalMachineRepair')->where($where)->find();
        if (!$check) {
            $machineUpdate['isRepair'] = 0;
            $where                     = [
                ['uuid', '=', $machineUuid],
                ['isDelete', '=', 0],
                ['projectCode', '=', $request->prjCode],
            ];
            DB::table('certificate_digitalMachine')->where($where)->update($machineUpdate);
        }
    }

    /**
     * @Description: 检修申请
     * @param {Request} $request
     */
    public function apply(Request $request)
    {
        $data          = $request->data;
        $wxappUserUuid = $request->uuid;

        $machineUuid = $data['machineUuid'];
        $machine     = DB::table('certificate_digitalMachine')
            ->alias('m')
            ->join('certificate_digitalMachineType t', 't.uuid = m.digitalMacineTypeUuid')
            ->where(['m.isDelete' => 0, 'm.uuid' => $machineUuid])->field('t.repairTypeUuid')
            ->find();
        if (!$machine) {
            return result(FAIL, '', '设备不存在');
        }

        $formData = is_array($data['formData']) ? json_encode($data['formData'], JSON_UNESCAPED_UNICODE) : $data['formData'];
        $formData = html_entity_decode($formData);

        $flowForm = Db::table('certificate_flowForm')->where('uuid', $data['flowFormUuid'])->find();
        if (!$flowForm) {
            return result(FAIL, '', '流程表单不存在');
        }

        DB::startTrans();
        try {
            //检修记录
            $repairData = [
                'title'         => $data['title'],
                'description'   => $data['description'],
                'flowFormUuid'  => $data['flowFormUuid'],
                'flowUuid'      => $flowForm['flowUuid'],
                'wxappUserUuid' => $wxappUserUuid,
                'status'        => 0,
                'uuid'          => createUuid(),
                'machineUuid'   => $machineUuid,
                'projectCode'   => $request->prjCode,
                'corpCode'      => $request->corpCode,
            ];
            DB::table('certificate_digitalMachineRepair')->insert($repairData);

            //提交表单记录
            $recordData = [
                'repairUuid'    => $repairData['uuid'],
                'flowFormUuid'  => $data['flowFormUuid'],
                'wxappUserUuid' => $wxappUserUuid,
                'uuid'          => createUuid(),
                'formData'      => $formData,
                'flowOrder'     => $flowForm['flowOrder'],
                'projectCode'   => $request->prjCode,
                'corpCode'      => $request->corpCode,
                'checkDate'     => $data['checkDate'] ?? date('Y-m-d H:i:s'),
            ];
            DB::table('certificate_digitalMachineRepairRecord')->insert($recordData);

            $machineUpdate['isRepair'] = 1;
            DB::table('certificate_digitalMachine')->where('uuid', $machineUuid)->where('isDelete', 0)->update($machineUpdate);
            //判断是否已经全部流程完成了
            $isFinish = $this->isFinish($repairData['uuid']);
            if ($isFinish) {
                $updateData['status']    = 1;
                $updateData['auditTime'] = date('Y-m-d H:i:s');

                $this->checkMachineStatus($machineUuid, $repairData['uuid'], $request);
            } else {
                //记录下一个可填写的表单
                $canSubForm                      = $this->canSubForm($repairData['uuid']) ?: [];
                $updateData['nextFlowFormUuids'] = json_encode($canSubForm, JSON_UNESCAPED_UNICODE);
            }
            DB::table('certificate_digitalMachineRepair')->where('uuid', $repairData['uuid'])->update($updateData);
            DB::commit();
            return result(SUCCESS, ['uuid' => $repairData['uuid']], '');
        } catch (\Exception $e) {
            return result(FAIL, '', $e->getMessage());
            DB::rollback();
        }
        return result(FAIL, '', '提交失败,请重试');
    }

    /**
     * @Description: 表单审核
     * @param {Request} $request
     */
    public function audit(Request $request)
    {
        $data          = $request->data;
        $wxappUserUuid = $request->uuid;

        $repairUuid    = $data['uuid'];
        $formData      = is_array($data['formData']) ? json_encode($data['formData'], JSON_UNESCAPED_UNICODE) : $data['formData'];
        $formData      = html_entity_decode($formData);
        $machineRepair = DB::table('certificate_digitalMachineRepair')->where(['isDelete' => 0, 'uuid' => $repairUuid])->find();
        if (!$machineRepair) {
            return result(FAIL, '', '检修申请记录不存在！');
        }

        if ($machineRepair['status'] == 1) {
            return result(FAIL, '', '该检修已审核通过');
        }

        //是否有审核权限
        $searchWhere = [
            ['ff.projectCode', '=', $request->prjCode],
            ['fw.wxappUserUuid', '=', $request->uuid],
            ['ff.formType', '=', 2],
            ['ff.isDelete', '=', 0],
            ['fw.isDelete', '=', 0],
            ['fw.flowFormUuid', '=', $data['flowFormUuid']],
        ];
        $auth = DB::table('certificate_flowForm')
            ->alias('ff')
            ->join('certificate_flow f', 'f.uuid=ff.flowUuid')
            ->join('certificate_flowFormWorker fw', 'ff.uuid=fw.flowFormUuid')
            ->where($searchWhere)
            ->find();
        if (empty($auth)) {
            return result(FAIL, '', '您没有审核权限');
        }

        DB::startTrans();
        try {
            $flowForm = Db::table('certificate_flowForm')->where('uuid', $data['flowFormUuid'])->find();
            if (!$flowForm) {
                return result(FAIL, '', '流程表单不存在');
            }

            //提交表单记录
            $recordData = [
                'repairUuid'    => $repairUuid,
                'flowFormUuid'  => $data['flowFormUuid'],
                'wxappUserUuid' => $wxappUserUuid,
                'uuid'          => createUuid(),
                'formData'      => $formData,
                'flowOrder'     => $flowForm['flowOrder'],
                'projectCode'   => $request->prjCode,
                'corpCode'      => $request->corpCode,
                'checkDate'     => $data['checkDate'] ?? date('Y-m-d H:i:s'),
            ];
            DB::table('certificate_digitalMachineRepairRecord')->insert($recordData);

            //判断是否已经全部流程完成了
            $isFinish = $this->isFinish($repairUuid);
            if ($isFinish) {
                $updateData['status']    = 1;
                $updateData['auditTime'] = date('Y-m-d H:i:s');
                $this->checkMachineStatus($machineRepair['machineUuid'], $repairUuid, $request);
            } else {
                //记录下一个可填写的表单
                $canSubForm                      = $this->canSubForm($repairUuid) ?: [];
                $updateData['nextFlowFormUuids'] = json_encode($canSubForm, JSON_UNESCAPED_UNICODE);
            }
            DB::table('certificate_digitalMachineRepair')->where('uuid', $repairUuid)->update($updateData);
            DB::commit();
            return result(SUCCESS, ['uuid' => $recordData['uuid']], '提交成功');
        } catch (\Exception $e) {
            DB::rollback();
        }
        return result(FAIL, '', '提交失败,请重试');
    }

    //本流程下待填写表单
    public function canSubForm($repairUuid, $isNext = 1, $flowUuid = '', $lastFlowFormUuid = '', $lastFlowOrder = 1, $lastType = 1)
    {
        // 是否直接获取下一个表单
        if ($isNext) {
            // 获取最近一个已填写的表单记录
            $record = DB::table('certificate_digitalMachineRepairRecord')
                ->alias('rr')
                ->join('certificate_digitalMachineRepair r', 'r.uuid = rr.repairUuid')
                ->join('certificate_flowForm ff', 'ff.uuid = rr.flowFormUuid')
                ->where('rr.repairUuid', '=', $repairUuid)
                ->field('rr.flowOrder, rr.uuid, r.flowUuid,  ff.type, rr.flowFormUuid')
                ->order('rr.flowOrder desc, rr.id desc')
                ->find();
            if (!$record) {
                return result(FAIL, '', '没有检修提交记录');
            }
            $flowUuid         = $record['flowUuid'];
            $lastFlowFormUuid = $record['flowFormUuid'];
            $lastFlowOrder    = $record['flowOrder'];
            $lastType         = $record['type'];
        }

        $nextFlowOrder   = $lastFlowOrder + 1;
        $canSubFormUUids = [];
        // 获取流表单数据
        $flowForms = DB::table('certificate_flowForm')
            ->where('flowUuid', '=', $flowUuid)
            ->where('isDelete', '=', 0)
            ->whereIn('flowOrder', [$lastFlowOrder, $nextFlowOrder])
            ->where('uuid', '<>', $lastFlowFormUuid)
            ->field(['uuid', 'flowOrder', 'signType'])
            ->select()
            ->toArray();
        // 处理流表单
        if (!empty($flowForms)) {
            $formUuids = array_column($flowForms, 'uuid');
            $signTypes = array_column($flowForms, 'signType');
            // 有多个表单并且存在 signType 1
            if (count($flowForms) > 1 && in_array(1, $signTypes)) {
                // 剔除当前的 lastFlowFormUuid
                $canSubFormUUids = array_filter($formUuids, function ($uuid) use ($lastFlowFormUuid) {
                    return $uuid !== $lastFlowFormUuid;
                });
            } else {
                $canSubFormUUids = $formUuids; // 直接取所有的 UUID
            }
            // 如果没有 signType 为 1
            if (!in_array(1, $signTypes)) {
                $nextFlowUuids = array_column(
                    array_filter($flowForms, function ($form) use ($nextFlowOrder) {
                        return $form['flowOrder'] == $nextFlowOrder;
                    }),
                    'uuid'
                );
                $canSubFormUUids = array_unique(array_merge($canSubFormUUids, $nextFlowUuids));
            }
        }

        return array_unique($canSubFormUUids);
    }
    /**
     * @Description: 获取字典
     * @param {Request} $request
     */
    public function getOptions(Request $request)
    {
        $where = array_merge(['isDelete' => 0], $request->authWhere);

        $searchWhere = [
            ['m.projectCode', '=', $request->prjCode],
            ['md.wxappUserUuid', '=', $request->uuid],
            ['md.isDelete', '=', 0],
            ['m.isDelete', '=', 0],
            ['m.status', '=', 1],
        ];
        $data['machineList'] = DB::table('certificate_digitalMachineDriver')
            ->alias('md')
            ->join('certificate_digitalMachine m', 'm.uuid=md.digitalMachineUuid')
            ->field(['m.name', 'm.uuid', 'm.subtitle'])
            ->where($searchWhere)
            ->select();
        return result(SUCCESS, $data);
    }

    /**
     * 获取设备详情
     *
     * @param Request $request
     * @return void
     */
    public function getMachineDetail(Request $request)
    {
        $data = $request->data;

        $machineUuid = $data['uuid'];
        $machine     = DB::table('certificate_digitalMachine')
            ->alias('m')
            ->join('certificate_digitalMachineType t', 't.uuid = m.digitalMacineTypeUuid')
            ->where(['m.isDelete' => 0, 'm.uuid' => $machineUuid])->field('t.repairTypeUuid')
            ->find();
        if (!$machine) {
            return result(FAIL, '', '设备不存在');
        }

        $uuid = $machine['repairTypeUuid'];

        $where = [
            'rt.isDelete'       => 0,
            'rt.repairTypeUuid' => $uuid,
            'ff.formType'       => 1,
            'ff.isDelete'       => 0,
        ];
        $typeData = DB::table('certificate_digitalMachineType')
            ->alias('rt')
            ->join('certificate_flow f', 'f.uuid=rt.repairTypeUuid')
            ->join('certificate_flowForm ff', 'ff.flowUuid=f.uuid')
            ->where($where)
            ->field(['rt.uuid', 'ff.formData', 'rt.name', 'ff.uuid as formUuid', 'ff.name as formName', 'ff.type'])
            ->find();
        if (empty($typeData)) {
            return result(FAIL, '', '獲取失敗，請返回重試');
        }

        $typeData['formData'] = json_decode(html_entity_decode($typeData['formData'] ?? ''), true) ?: [];
        //是否有下一步操作
        $typeData['hasNext'] = $this->hasNextByMachineUuid($typeData['uuid'], $request->uuid);
        return result(SUCCESS, $typeData, '');
    }

    //检修流程是否已经完成
    public function isFinish($repairUuid)
    {
        $isFinish = 0;
        //获取最近一个已填写的表单记录
        $record = DB::table('certificate_digitalMachineRepairRecord')
            ->alias('rr')
            ->join('certificate_digitalMachineRepair r', 'r.uuid = rr.repairUuid')
            ->join('certificate_flowForm ff', 'ff.uuid = rr.flowFormUuid')
            ->where([
                ['rr.repairUuid', '=', $repairUuid],
            ])
            ->order('rr.flowOrder desc,rr.id desc') // 按照流程顺序降序排列
            ->find();

        if (!$record) {
            return result(FAIL, '', '没有检修提交记录');
        }
        $nextFlowOrder   = $record['flowOrder'] + 1;
        $canSubFormUUids = [];
        $flowForm        = DB::table('certificate_flowForm')
            ->where([
                ['flowUuid', '=', $record['flowUuid']],
                ['isDelete', '=', 0],
                ['flowOrder', '=', $record['flowOrder']],
            ])->select()->toArray();
        $recordCount = DB::table('certificate_digitalMachineRepairRecord')
            ->alias('rr')
            ->join('certificate_digitalMachineRepair r', 'r.uuid = rr.repairUuid')
            ->where([
                ['r.flowUuid', '=', $record['flowUuid']],
                ['rr.isDelete', '=', 0],
                ['rr.flowOrder', '=', $record['flowOrder']],
            ])->count();
        if (count($flowForm) > 1 && in_array(1, array_column($flowForm, 'signType')) && $recordCount != count($flowForm)) {
            $canSubFormUUids = DB::table('certificate_flowForm')
                ->where([
                    ['flowUuid', '=', $record['flowUuid']],
                    ['isDelete', '=', 0],
                    ['flowOrder', '=', $record['flowOrder']],
                    ['uuid', '<>', $record['flowFormUuid']],
                ])->column('uuid');
        } else {
            $canSubFormUUids = DB::table('certificate_flowForm')
                ->where([
                    ['flowUuid', '=', $record['flowUuid']],
                    ['isDelete', '=', 0],
                    ['flowOrder', '=', $nextFlowOrder],
                ])->column('uuid');
        }
        if (!$canSubFormUUids) {
            $isFinish = 1;
        }

        return $isFinish;
    }

    /**
     * 获取表单提交详情
     *
     * @param Request $request
     * @return void
     */
    public function getRecordDetail(Request $request)
    {
        $data  = $request->data;
        $uuid  = $data['uuid'];
        $where = [
            'r.isDelete' => 0,
            'r.uuid'     => $uuid,
        ];
        //查看提交过的记录
        $returnData = DB::table('certificate_digitalMachineRepairRecord')
            ->alias('r')
            ->join('certificate_flowForm f', 'f.uuid = r.flowFormUuid')
            ->where($where)
            ->field('f.uuid,f.name,f.subtitle,r.formData,f.linkForms')
            ->find();
        if (!$returnData) {
            return result(FAIL, '', '没有提交记录');
        }

        $returnData['formData'] = json_decode(html_entity_decode($returnData['formData']), true);

        $linkForms = $returnData['linkForms'] ? json_decode($returnData['linkForms'], true) : [];
        if ($linkForms) {
            $linkForms = DB::table('certificate_flowForm')
                ->alias('ff')
                ->join('certificate_digitalMachineRepairRecord r', 'r.flowFormUuid = ff.uuid')
                ->whereIn('ff.uuid', $linkForms)
                ->order('ff.showOrder asc,ff.flowOrder asc,r.id asc')
                ->field('r.uuid,ff.name,r.formData')
                ->group('r.uuid')
                ->select()->toArray();
            foreach ($linkForms as $key => $item) {
                $linkForms[$key]['formData'] = json_decode(html_entity_decode($item['formData']), true);
            }
        }
        $returnData['linkForms'] = $linkForms;

        return result(SUCCESS, $returnData, '');
    }

    //获取当前用户待提交表单的检修
    public function getCurrentToSubFormUuids($wxappUserUuid)
    {
        //当前已经提交的流程表单
        $flowFormUuid = DB::table('certificate_digitalMachineRepairRecord')
            ->alias('r')
            ->join('certificate_digitalMachineRepair mr', 'mr.uuid =  r.repairUuid')
            ->where('r.wxappUserUuid', $wxappUserUuid)
            ->where('mr.status', 0)
            ->column('r.flowFormUuid') ?? [];
        //获取当前用户拥有的待审批表单
        $flowFormUuids = DB::table('certificate_flowFormWorker')
            ->alias('w')
            ->join('certificate_flowForm ff', 'w.flowFormUuid=w.flowFormUuid')
            ->where('w.wxappUserUuid', $wxappUserUuid)
            ->where('ff.formType', 2)
            ->where('w.isDelete', 0)
            ->whereNotIn('ff.uuid', $flowFormUuid)
            ->group('w.flowFormUuid')
            ->column('w.flowFormUuid') ?: [];
        $flowFormUuids = array_unique($flowFormUuids);
        $arrList       = DB::table('certificate_digitalMachineRepair')
            ->alias('r')
            ->where('r.nextFlowFormUuids', '<>', '')
            ->where('r.status', 0)
            ->field(['r.uuid', 'r.nextFlowFormUuids'])
            ->group('r.id')
            ->select()
            ->toArray();
        $arrList = array_filter($arrList, function ($item) use ($flowFormUuids) {
            $nextFlowFormUuids = json_decode($item['nextFlowFormUuids'], true);
            if (array_intersect($flowFormUuids, $nextFlowFormUuids)) {
                return true;
            }
            return false;
        });
        return array_column($arrList, 'uuid') ?: [];
    }

    public function getToSubCount($getCurrentToSubFormUuids, $data)
    {
        //待填写数量
        $searchWhere = [];
        array_push($searchWhere, ['r.uuid', 'IN', $getCurrentToSubFormUuids]);
        array_push($searchWhere, ['r.status', '=', 0]);
        array_push($searchWhere, ['r.machineUuid', '=', $data['machineUuid']]);
        array_push($searchWhere, ['w.isDelete', '=', 0]);
        $toSubCount = DB::table('certificate_digitalMachineRepair')
            ->alias('r')
            ->join('certificate_flowFormWorker w', 'w.wxappUserUuid = r.wxappUserUuid')
            ->where($searchWhere)
            ->group('r.id')
            ->count();
        return $toSubCount ?: 0;
    }

    public function hasAuth($request, $data)
    {
        //是否有新增权限,具有申请表权限+驾驶舱人员
        $hasAuth     = 0;
        $isDriver    = 1;
        $searchWhere = [
            ['mt.projectCode', '=', $request->prjCode],
            ['fw.wxappUserUuid', '=', $request->uuid],
            ['mt.isDelete', '=', 0],
            ['fw.isDelete', '=', 0],
            ['ff.formType', '=', 1],
        ];

        if (!empty($data['machineUuid'])) {
            //是否有驾驶员权限
            $isDriver = DB::table('certificate_digitalmachinedriver')
                ->where([
                    'isDelete'           => 0,
                    'wxappUserUuid'      => $request->uuid,
                    'digitalMachineUuid' => $data['machineUuid'],
                ])->value('id');
            //获取设备类型，并确认设备是否离场
            $typeUuid = DB::table('certificate_digitalMachine')
                ->where([
                    'projectCode' => $request->prjCode,
                    'uuid'        => $data['machineUuid'],
                    'status'      => 1,
                ])->value('digitalMacineTypeUuid');
            if (!$typeUuid) {
                return 0;
            }

            array_push($searchWhere, ["mt.uuid", '=', $typeUuid]);
        }

        $flowAuth = DB::table('certificate_digitalMachineType')
            ->alias('mt')
            ->join('certificate_flow f', 'f.uuid=mt.repairTypeUuid')
            ->join('certificate_flowForm ff', 'ff.flowUuid=f.uuid')
            ->join('certificate_flowFormWorker fw', 'ff.uuid=fw.flowFormUuid')
            ->where($searchWhere)
            ->value('rt.id');
        return (int) ($isDriver && $flowAuth);
    }

    public function hasNextByMachineUuid($machineTypeUuid, $wxappUserUuid)
    {
        $hasNext = 0;
        $where   = [
            'rt.isDelete' => 0,
            'rt.uuid'     => $machineTypeUuid,
            'ff.formType' => 1,
            'ff.isDelete' => 0,
        ];
        $record = DB::table('certificate_digitalMachineType')
            ->alias('rt')
            ->join('certificate_flow f', 'f.uuid=rt.repairTypeUuid')
            ->join('certificate_flowForm ff', 'ff.flowUuid=f.uuid')
            ->where($where)
            ->field(['rt.uuid', 'ff.flowUuid', 'ff.uuid as flowFormUuid', 'ff.type'])
            ->find();
        if ($record) {
            //本流程下可提交的表单
            $nextFlowOrder       = 2;
            $canSubFormUUids     = [];
            $canNextSubFormUUids = DB::table('certificate_flowForm')
                ->where([
                    ['flowUuid', '=', $record['flowUuid']],
                    ['isDelete', '=', 0],
                    ['flowOrder', '=', $nextFlowOrder],
                ])->column('uuid');
            $canSubFormUUids = array_merge($canSubFormUUids, $canNextSubFormUUids);
            //获取当前用户拥有的表单信息
            $nextData = DB::table('certificate_flowForm')
                ->alias('ff')
                ->join('certificate_flowFormWorker fw', 'fw.flowFormUuid = ff.uuid')
                ->where([
                    'fw.wxappUserUuid' => $wxappUserUuid,
                    'fw.isDelete'      => 0,
                ])
                ->whereIn('ff.uuid', $canSubFormUUids)
                ->order('ff.flowOrder asc')
                ->field('ff.uuid')
                ->find();
            if ($nextData) {
                $hasNext = 1;
            }

        }
        return $hasNext;
    }

    /**
     * @Description: 根据流程uuid获取流程表单列表
     * @return {type}
     * @param {Request} $request
     */
    public function accordFlowUuidGetFlowFormList(Request $request)
    {
        $data     = $request->data;
        $flowUuid = $data['flowUuid'];

        $where = [
            'ff.flowUuid' => $flowUuid,
            'ff.isDelete' => 0,
        ];
        $list = DB::table('certificate_flow')
            ->alias('f')
            ->join('certificate_flowForm ff', 'ff.flowUuid = f.uuid')
            ->where($where)
            ->order('ff.flowOrder asc,ff.showOrder asc')
            ->field('ff.uuid as flowFormUuid,ff.flowOrder,ff.name,ff.subtitle,ff.formType,ff.formData')
            ->select()->toArray();

        foreach ($list as &$value) {
            $value['formData'] = json_decode(html_entity_decode($value['formData']), true) ?? [];
        }
        return result(SUCCESS, $list, '');
    }
}
